package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import parser.PedidoVentaXtream;

import clienteWeb.ClienteWeb;

import beans.ClienteBean;
import beans.ItemPedidoVentaBean;
import beans.PedidoVentaBean;
import beans.RodamientoBean;
 
public class ProcesarPedidoVenta extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
   
    public ProcesarPedidoVenta() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		ClienteBean cliente = new ClienteBean();
		cliente.setCuit( request.getParameter("cuit") );
		
		PedidoVentaBean pedidoVenta = new PedidoVentaBean();
		pedidoVenta.setCliente( cliente );
		
		String[] arrayItems = request.getParameter("items").split(",");
		 
		for (int i = 0; i < arrayItems.length; i++) 
		{
			String[] arrayValores = arrayItems[i].split(":");
			
			if(!(arrayValores[0].isEmpty()))
			{
				ItemPedidoVentaBean item = new ItemPedidoVentaBean();
				RodamientoBean rodamiento = ClienteWeb.getInstancia().consultarRodamiento(arrayValores[0]);
				
				if(rodamiento != null)
				{
					List<ItemPedidoVentaBean> listaItems = new ArrayList<ItemPedidoVentaBean>();
					item.setCantidad(Integer.parseInt(arrayValores[1]));
					item.setRodamiento( rodamiento );
					listaItems.add(item);
					pedidoVenta.setItems( listaItems );
				}
			}
			System.out.println(arrayItems[i]);
		}
		
		//Genero El Pedido de Ventas...
		ClienteWeb.getInstancia().generarPedidoVenta( pedidoVenta );
		
	    //Genero el XML...
		response.setContentType("application/octet-stream");
	    response.setHeader("Content-Disposition", "attachement; filename=PedidoVenta.xml");
		PedidoVentaXtream parser = new PedidoVentaXtream();
		String xml = parser.toXML( pedidoVenta );

		PrintWriter output = response.getWriter();
		output.println(xml.toString());
		output.close();
	}

}

